import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import {
	GetTitleEntity,
	initialState,
	MeetingEntity,
	MeetingListPageEntity,
	ValidLinkProps,
	_MeetingEntity,
} from './interface'
import { useStore as useShareModalStore } from '@/components/ShareModal/store'

import { fetchConflictMeeting, fetchFeedBack, fetchGetIsValidLink, fetchGetMeetingList } from '@/api/meetingList'
import { Utils } from './MeetingCard/utils'
import { useGlobalStore } from '@/store/global'
import Alert from '@/components/Alert'
import jumpPage from '@/utils/jumpPage'
import Icon from '@/components/Icon'
import { Message, Trigger } from '@kedacom/react-next'
import { fetchStatus } from '@/api/global'
import dayjs from '@/plugins/dayjs'
import { t } from 'i18next'
import { IUser } from '@/api/global/interface'
import Room from '../detail/content/room'
import { getMeetingTime, getRegularMeetingTime } from '@/utils'

type MeetingScheduleStore = MeetingListPageEntity & {
	update: (d: Partial<MeetingListPageEntity>) => void
	/**获取正在召开的会议*/
	AjaxFetchBeBeginHeldMeetingList: (loadMaskRef?: React.MutableRefObject<any>) => void
	/**获取预约的会议*/
	AjaxFetchAppointmentMeetingList: (loadMaskRef?: React.MutableRefObject<any>) => void
	/**获取不参加的会议*/
	AjaxFetchAuditMeetingList: (loadMaskRef?: React.MutableRefObject<any>) => void
	/**获取不参加的会议*/
	AjaxFetchNotParticipateMeetingList: (loadMaskRef?: React.MutableRefObject<any>) => void
	/**加载冲突的会议 第二个参数代表详情trgger  ref引用*/
	AjaxFetchConflictMeeting: (_meeting: MeetingEntity) => void
	/**进入会议详情*/
	handleIntoMeetingDetail: (meeting_id: string) => void
	/**编辑会议*/
	handleEditMeeting: (meeting_id: string) => void
	/**获取会议名称*/
	getTitle: (_params: GetTitleEntity) => React.ReactElement
	/**获取会议的e164号 */
	getMeetingE164: (_meeting: MeetingEntity, default_show: boolean) => React.ReactElement

	getMeetingTimeContent: (_meeting: MeetingEntity, is_conflict_modal?: boolean) => React.ReactElement

	/**获取会议室*/
	getMeetingRooms: (_meeting: MeetingEntity, _ref: React.MutableRefObject<any>) => React.ReactElement
	/**获取组织者 */
	getOrganigerInfo: (_meeting: MeetingEntity) => React.ReactElement
	/**进入会议空间 */
	// actionIntoMeetingSpace: (_meeting: MeetingEntity) => React.ReactElement
	/**获取对应的域名称只在正在召开的会议当中存在*/
	getDomainName: (_meeting: MeetingEntity, user: IUser | null) => React.ReactElement
	/**获取右上角的会议图标*/
	getRightTopMeetingIcon: (_meeting: MeetingEntity) => React.ReactElement
	/**获取会议加密背景 */
	getWrapBgClassName: (_meeting: MeetingEntity) => string
	/**获取参会人数*/
	getAttendingPersonNum: (_meeting: MeetingEntity) => React.ReactElement
	/**分享会议 */
	handleShare: (_meeting: MeetingEntity) => void
	/**获取加密类型*/
	getMeetingEncryptionType: (_meeting: MeetingEntity) => string
	/**是否是永久会议*/
	isPermanent: (_meeting: MeetingEntity) => 0 | 1
	/**是否有会议冲突*/
	isConflict: (_meeting: MeetingEntity) => boolean
	/**是否是例会*/
	isRepeat: (meeting: MeetingEntity) => boolean
	/**用户是否才存在enable_meeting权限 */
	isUserEnableMeeting: () => boolean
	/**用户的审批权限*/
	// isUserEnableCmsApproval: () => boolean
	/**预约会议查看全部 */
	handleSeeAll: () => void
	/**根据时长（分钟）获取对应的小时和分钟*/
	getDuration: (duration: number) => { hour: number; minute: number }
	/**错误处理*/
	failure: (msg: string) => void
	/**参加会议 */
	actionParticipate: (_meeting: MeetingEntity) => void
	/**加入会议 */
	actionJoinMeeting: (_meeting: MeetingEntity) => void
	/**检测链接是否可用 */
	isValidLink: (_params: ValidLinkProps, callBack?: () => void) => void
	/**参会反馈 */
	participate: (callback?: () => void) => void
}
export const store = createVanilla<MeetingScheduleStore>((set, get) => ({
	...initialState,
	update: (d) => set({ ...d }),
	/*
	函数的使用
	1. 刚进入页面获得列表数据
	const loadMaskRef = useRef<any>(null)
	loadMaskRef.current = Message.loading(t('正在加载会议列表，请稍候……'))
	AjaxFetchBeBeginHeldMeetingList(loadMaskRef)

	2.结束会议后，刷新列表数据
	AjaxFetchBeBeginHeldMeetingList()

	// 获取正在召开的会议
	AjaxFetchBeBeginHeldMeetingList: (loadMaskRef?: React.MutableRefObject<any>) => void
	
	# 创建ref
	ref有两种类型：MutableRefObject 和 RefObject.
	这两种类型都有 current 字段

	鼠标移动到 loadMaskRef 显示
	const loadMaskRef: React.MutableRefObject<any>

	*/
	AjaxFetchBeBeginHeldMeetingList: async (loadMaskRef) => {
		let _request_params = { state: 2, start_time: dayjs('1970-01-01').format(), count: 0 }
		const _res = await fetchGetMeetingList(_request_params)
		loadMaskRef && loadMaskRef.current?.hide() /**隐藏蒙层*/
		if (_res && _res.success) {
			set({
				beBegin_held_list: _res.meetings.map((item) => new MeetingEntity(item as _MeetingEntity)),
				beBegin_held_ajax_finish: true,
				is_show_beBegin_held: true,
			}) /**请求结束 */
		} else {
			set({
				beBegin_held_list: [],
				beBegin_held_ajax_finish: true,
				is_show_beBegin_held: false,
			}) /**请求结束 */
			Alert(t('会议列表加载异常，请重试！')) /**弹框提示 */
		}
	},
	AjaxFetchAppointmentMeetingList: async (loadMaskRef) => {
		let _request_params = {
			state: 1,
			count: 10,
			end_time: dayjs(new Date()).add(7, 'days').startOf('day').format(),
		}
		const _res = await fetchGetMeetingList(_request_params)
		loadMaskRef && loadMaskRef.current?.hide() /**隐藏蒙层*/
		/**请求结束 */
		if (_res && _res.success) {
			set({
				appointment_list: _res.meetings.map((item) => new MeetingEntity(item as _MeetingEntity)),
				appointment_ajax_finish: true,
				is_show_appointment: true,
				appointment_list_total: _res.total,
			})
		} else {
			set({
				appointment_list: [],
				is_show_appointment: false,
				appointment_ajax_finish: true,
				appointment_list_total: 0,
			})
			Alert(t('会议列表加载异常，请重试！')) /**弹框提示 */
		}
	},
	AjaxFetchAuditMeetingList: async (loadMaskRef) => {
		const user = useGlobalStore.getState().user
		if (!user?.enable_cms_approval) {
			let pass_params = { state: 6, start_time: dayjs('1970-01-01').format(), count: 0 }
			let no_pass_params = { state: 7, start_time: dayjs('1970-01-01').format(), count: 0 }
			Promise.all([fetchGetMeetingList(pass_params), fetchGetMeetingList(no_pass_params)]).then((values) => {
				let list = []
				let error_flag = false
				if (values[0] && values[0].success) {
					list.push(...values[0].meetings)
				} else {
					error_flag = true
				}
				if (values[1] && values[1].success) {
					list.push(...values[1].meetings)
				} else {
					error_flag = true
				}
				loadMaskRef && loadMaskRef.current?.hide() /**隐藏蒙层*/
				if (error_flag) {
					Alert(t('会议列表加载异常，请重试！')) /**弹框提示 */
				} else {
					set({
						audited_list: list.map((item) => new MeetingEntity(item as _MeetingEntity)),
						audited_ajax_finish: true,
						is_show_audited: true,
					})
				}
			})
		} else {
			set({ audited_ajax_finish: true, is_show_audited: false })
		}
	},
	AjaxFetchNotParticipateMeetingList: async (loadMaskRef) => {
		let _request_params = { state: 10, count: 0 }
		const _res = await fetchGetMeetingList(_request_params)
		loadMaskRef && loadMaskRef.current?.hide() /**隐藏蒙层*/
		if (_res && _res.success) {
			set({
				not_participate_list: _res.meetings.map((item) => new MeetingEntity(item as _MeetingEntity)),
				not_participate_ajax_finish: true,
				is_show_not_participate: true,
			}) /**请求结束 */
		} else {
			set({
				not_participate_list: [],
				not_participate_ajax_finish: true,
				is_show_not_participate: false,
			}) /**请求结束 */
			Alert(t('会议列表加载异常，请重试！')) /**弹框提示 */
		}
	},
	handleIntoMeetingDetail: (meeting_id: string) => {
		jumpPage('detail', meeting_id)
	},

	/**
	 *
	 * @param meeting_id meetingMoid
	 */
	handleEditMeeting: (meeting_id: string) => {
		const flag = get().isUserEnableMeeting()
		if (flag) {
			fetchStatus(() => {
				jumpPage('create', meeting_id)
			})
		}
	},
	getDuration: (duration: number) => {
		let _hour = parseInt((duration / 60).toString())
		return {
			hour: _hour,
			minute: duration - 60 * _hour,
		}
	},
	getTitle: (_props) => {
		const { _meeting, is_show_share = false, is_show_vcs = false, is_show_edit = false } = _props
		const { handleShare, handleIntoMeetingDetail, handleEditMeeting } = get()
		const { conf_category, super_mt_num = 0, name = '', max_join_mt = 192, meeting_id, is_edit } = _meeting
		const SWITCH = useGlobalStore.getState().SWITCH
		return (
			<div className="meeting-card-meeting-name-info-wrap">
				{/* 只有正在召开的会议才判断*/}
				<div
					className="meeting_name"
					onClick={() => {
						const user = useGlobalStore.getState().user
						if (!user?.enable_meeting) {
							Alert(t('无会议管理权限，请通知管理员'))
							return false
						}
						handleIntoMeetingDetail(meeting_id)
					}}
				>
					{is_show_vcs && <span>{conf_category === 1 ? '[VCS]' : ''}</span>}
					{super_mt_num > 0 && <span style={{ paddingRight: '4px' }}>{t('[超大方]')} </span>}
					{max_join_mt !== 192 ? (
						<span style={{ paddingRight: '4px' }}>[{t('{{num}}方', { num: max_join_mt })}]</span>
					) : null}
					<span title={name} className="nameSpan">
						{name}
					</span>
				</div>

				{is_show_share && !!SWITCH.share && (
					<span
						className="share_btn"
						onClick={() => {
							handleShare(_meeting)
						}}
					>
						{t('分享')}
					</span>
				)}
				{/* 审批和预约会议才会展示可编辑 */}
				{is_show_edit && (
					<span
						title={t('编辑')}
						className="edit_btn"
						onClick={(e) => {
							e.stopPropagation()
							handleEditMeeting(meeting_id)
						}}
					></span>
				)}
			</div>
		)
	},
	getMeetingE164: (_meeting) => {
		/**default_show 审批会议/不参加会议   false   预约会议/正在召开的会议*/
		return <span>{t('会议号码（{{num}}）', { num: _meeting.conf_id })}</span>
	},
	/**获取会议时间*/
	getMeetingTimeContent: (_meeting, is_conflict_modal) => {
		const { is_attendee, duration, meeting_formular } = _meeting
		const { start_date = '', end_date = '', week_days = '' } = meeting_formular
		const { isPermanent, isConflict, AjaxFetchConflictMeeting, isRepeat } = get()
		/**表示是参与者且冲突*/
		const _flag = !!(is_attendee === 1 && isConflict(_meeting))
		if (isRepeat(_meeting)) {
			let text = getRegularMeetingTime(_meeting.start_time, _meeting.duration, {
				start_date,
				end_date,
				week_days,
			})
			return <div title={text}>{text}</div>
		} else {
			return (
				<>
					<div className={`${_flag && !is_conflict_modal ? 'time_content_conflict' : ''}`}>
						<span>{getMeetingTime(_meeting.start_time, duration, Boolean(isPermanent(_meeting)))}</span>
						{_flag && !is_conflict_modal && (
							<span
								className="time_content_tag"
								onClick={() => {
									AjaxFetchConflictMeeting(_meeting)
								}}
							>
								{t('会议冲突')}
							</span>
						)}
					</div>
				</>
			)
		}
	},
	AjaxFetchConflictMeeting: async (_meeting: MeetingEntity) => {
		const flag = get().isUserEnableMeeting()
		if (flag) {
			const { meeting_id } = _meeting
			let m = Message.loading(t('正在加载冲突的会议，请稍候……'))
			setTimeout(() => {
				m.hide()
			}, 500)
			const res = await fetchConflictMeeting(meeting_id)
			if (res.success) {
				/**设置冲突会议 */
				set({
					conflict_list: res.meetings.map((item) => new MeetingEntity(item as _MeetingEntity)),
					is_show_conflict_meeting_modal: true,
				})
				m.hide()
			} else {
				m.hide()
				Alert(res.description || t('加载冲突会议失败'))
			}
		}
	},

	getMeetingRooms: (_meeting: MeetingEntity, _ref) => {
		const { video, meeting_rooms, crossPlatform } = _meeting
		const { isRepeat } = get()
		let flag = !meeting_rooms || meeting_rooms.length === 0 || crossPlatform
		if (flag) {
			return <></>
		} else {
			if (isRepeat(_meeting)) {
				return meeting_rooms && meeting_rooms.length !== 0 ? (
					<div className="meeting-card-body-line meeting-card-meeting-rooms-info">
						<Trigger
							popup={<Room rooms={_meeting.rooms} isRepeat={true}></Room>}
							popupAlign={{ offset: [200, 3] }}
						>
							<span className="rooms_detail">{t('会议室详情')}</span>
						</Trigger>
					</div>
				) : (
					<></>
				)
			} else {
				return (
					<div className="meeting-card-body-line meeting-card-meeting-rooms-info">
						<span className="ellipsis" style={{ paddingRight: '4px' }} title={meeting_rooms.join('、')}>
							{meeting_rooms.join('、')}
						</span>
						{video && (
							<>
								<Trigger
									popup={<Room rooms={_meeting.rooms} isRepeat={false}></Room>}
									popupAlign={{ offset: [200, 3] }}
								>
									<span className="rooms_detail">{t('会议室详情')}</span>
								</Trigger>
							</>
						)}
					</div>
				)
			}
		}
	},

	getOrganigerInfo: (_meeting) => {
		const { creator } = _meeting
		const { name, telephone, mobile } = creator
		let _msg = ''
		if (telephone && mobile) {
			_msg = `${name}（${Utils.code.encodeHTML(mobile)}/${Utils.code.encodeHTML(telephone)}）`
		} else if (telephone || mobile) {
			_msg = `${name}（${Utils.code.encodeHTML(telephone) || Utils.code.encodeHTML(mobile)}）`
		} else {
			_msg = `${name}`
		}
		return <span title={_msg}>{_msg}</span>
	},
	getDomainName: (_meeting, user) => {
		/**只有正在召开的会议展示*/
		const user_domain_name = _meeting.user_domain_name || ''
		return (
			<>
				{user_domain_name !== '' && user_domain_name !== user?.user_domain_name && (
					<div className="meeting-card-body-line meeting_info_domain_name">
						<div className="meeting-card-span-organiger">
							{t('召开在{{name}}', { name: user_domain_name })}
						</div>
					</div>
				)}
			</>
		)
	},
	/**获取右上角的会议图标*/
	getRightTopMeetingIcon: (_meeting: MeetingEntity) => {
		const { QT_MEETING, AES_MEETING, GM_MEETING, getMeetingEncryptionType } = get()
		const meetingEncryptionType = getMeetingEncryptionType(_meeting)
		const { cascade_meeting, video, isRegularMeeting } = _meeting
		return (
			<>
				{meetingEncryptionType === QT_MEETING && (
					<Icon className="quantumEncryption qtmeeting " title={t('量子加密')}></Icon>
				)}
				{!!isRegularMeeting && <Icon className="quantumEncryption rmmeeting" title={t('例会')}></Icon>}
				{meetingEncryptionType === AES_MEETING && (
					<Icon className="quantumEncryption aesmeeting " title={t('aes加密')}></Icon>
				)}

				{meetingEncryptionType === GM_MEETING && (
					<Icon className="quantumEncryption gmeeting " title={t('国密加密')}></Icon>
				)}

				{!!cascade_meeting && <Icon className="quantumEncryption cmeeting " title={t('级联会议')}></Icon>}
				{!!video && <Icon className="quantumEncryption vmeeting" title={t('视频会议')}></Icon>}
			</>
		)
	},
	getAttendingPersonNum: (_meeting: MeetingEntity) => {
		const _attending_person_num = _meeting.attending_person_num || 0
		return (
			<>
				{_attending_person_num > 0 && (
					<div className="fixed-right-line">{t('共{{num}}位与会方', { num: _attending_person_num })}</div>
				)}
			</>
		)
	},
	/**获取加密类型*/
	getMeetingEncryptionType: (_meeting: MeetingEntity) => {
		const { QT_MEETING, AES_MEETING, GM_MEETING } = get()
		const { quantum_encryption = 0, encrypted_type = 0 } = _meeting
		if (quantum_encryption === 1 /**量子加密 */) {
			return QT_MEETING
		} else if (encrypted_type === 2 /**AES加密会议 */) {
			return AES_MEETING
		} else if ((encrypted_type === 3 || encrypted_type === 4) && quantum_encryption === 0 /**国密加密会议 */) {
			return GM_MEETING
		} else {
			return ''
		}
	},
	handleShare: (meeting: MeetingEntity) => {
		const user = useGlobalStore.getState().user
		if (!user?.enable_meeting) {
			Alert(t('无会议管理权限，请通知管理员'))
			return false
		}
		const { name, meeting_id, conf_id, start_time, duration } = meeting
		useShareModalStore.setState({
			meetingInfo: {
				name: name,
				e164: conf_id,
				meetingMoid: meeting_id,
				duration: duration,
				startTime: start_time,
			},
			type: 'meeting',
			open: true,
		})
	},
	isPermanent: (meeting) => {
		return (meeting.duration ?? 0) === 0 ? 1 : 0
	},

	isConflict: (meeting) => {
		return (meeting.is_conflict ?? 0) === 1
	},
	isRepeat: (meeting) => {
		return meeting.isRegularMeeting == 1
	},
	isUserEnableMeeting: () => {
		const user = useGlobalStore.getState().user
		if (!user?.enable_meeting) {
			Alert(t('无会议管理权限，请通知管理员'))
			return false
		}
		return true
	},
	// isUserEnableCmsApproval: () => {
	// 	const user = useGlobalStore.getState().user
	// 	return !!user?.enable_cms_approval
	// },
	handleSeeAll: () => {
		jumpPage('myMeeting', '', '?tabFlag=week')
	},
	getWrapBgClassName: (_meeting: MeetingEntity) => {
		const { QT_MEETING, AES_MEETING, GM_MEETING, getMeetingEncryptionType } = get()
		switch (getMeetingEncryptionType(_meeting)) {
			case GM_MEETING:
				return 'gm_meeting_bg'
			case AES_MEETING:
				return 'aes_meeting_bg'
			default:
				return 'hidden'
		}
	},
	failure: (msg) => {
		if (msg) {
			Alert(msg, function () {
				jumpPage('meetingList')
			})
		} else {
			Alert(t('操作失败!'))
		}
	},
	/**参加会议 */
	actionParticipate: (_meeting: MeetingEntity) => {
		const { meeting_id, video, last_modify_time, isRegularMeeting } = _meeting
		const { isValidLink } = get()
		/**是否例会(审批列表中显示例会样式，其余以普通会议显示)*/
		let person_attend_info = {
			isVideoMeeting: video,
			isParticipated: 1,
			participatedType: 1,
			meetingMoid: meeting_id,
			participatedNO: '',
			reasonId: '',
		}
		set({
			attending_info: { ...person_attend_info },
		})
		if (video) {
			// that.parent.participanteType.init(
			// 	lastModifyTime,
			// 	personAttendingInfo,
			// 	isRegularMeeting,
			// 	$(this),
			// 	meetingType
			// )
		} else {
			isValidLink({
				last_modify_time,
				meeting_moid: meeting_id,
				is_regular_meeting: isRegularMeeting,
			})
		}
	},
	actionJoinMeeting: async () => {},
	isValidLink: async (_params: ValidLinkProps, callBack) => {
		const res = await fetchGetIsValidLink(_params)
		if (res.success) {
			if (res.data) {
				get().participate(callBack)
			} else {
				Alert(t('该链接已失效'), function () {
					jumpPage('meetingList')
				})
			}
		} else {
			Alert(t('检查链接是否可用失败!'))
		}
	},
	participate: async (callback) => {
		const { attending_info, AjaxFetchNotParticipateMeetingList, AjaxFetchAppointmentMeetingList } = get()
		if (attending_info) {
			let _params = {
				is_participate: attending_info?.isParticipated,
				participate_type: attending_info?.participatedType,
				participated_no: attending_info?.participatedNO,
				reason_desc: attending_info?.reasonDesc,
				reason_type: attending_info?.reasonId,
			}
			let meeting_id = attending_info?.meetingMoid
			const res = await fetchFeedBack(_params, meeting_id)
			if (res.success) {
				callback && callback()
				AjaxFetchAppointmentMeetingList() //预约的会议
				AjaxFetchNotParticipateMeetingList()
			} else {
				Alert(t('操作失败!'))
			}
		}
	},
}))

export const useStore = create(store)
